package com.local.videoplayer.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.local.videoplayer.utils.SystemBarTintManager;
import java.lang.reflect.Field;

/**
 * Created by ccx on 16/05/18.
 * Activity基类
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 传递参数
     */
    public Bundle intentData;
    /**
     * 参数传递标示
     */
    public static final String PARAM_INTENT = "intentData";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intentData = getIntent().getBundleExtra(PARAM_INTENT);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        applyKitKatTranslucency();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content);
        rootView.setPadding(0, new SystemBarTintManager(this).getConfig()
                                                             .getStatusBarHeight(), 0, 0);
    }

    /**
     * 初始化页面传递过来的数据
     *
     * @param bundle
     *         数据
     */
    protected void initIntentData(Bundle bundle) {

    }

    @Override
    protected void onDestroy() {
        fixInputMethodManagerLeak(this);
        super.onDestroy();
    }

    public void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm =
                (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[] { "mCurRootView", "mServedView", "mNextServedView" };
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() ==
                            destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                        //if (QLog.isColorLevel()) {
                        //    QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
                        //}
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    protected <T extends View> T findViewByIdExt(int resId) {
        return (T) findViewById(resId);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        // overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void finish() {
        super.finish();
        //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onClick(View v) {

    }

    public void goToOthers(Class<?> cls) {
        goToOthers(cls, null);
    }

    public void goToOthersF(Class<?> cls) {
        goToOthers(cls);
        finish();
    }

    public void goToOthers(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(PARAM_INTENT, bundle);
        startActivity(intent);
    }

    public void goToOthersF(Class<?> cls, Bundle bundle) {
        goToOthers(cls, bundle);
        finish();
    }

    public void upToHome(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(PARAM_INTENT, bundle);
        startActivity(intent);
        finish();
    }

    public void upToHome(Class<?> cls) {
        upToHome(cls, null);
    }

    public void homeAction() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// ע��
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    public void goToOthersForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(PARAM_INTENT, bundle);
        startActivityForResult(intent, requestCode);
    }

    public void backForResult(Class<?> cls, Bundle bundle, int resultCode) {
        Intent intent = new Intent();
        if (cls != null) {
            intent.setClass(this, cls);
        }
        intent.putExtra(PARAM_INTENT, bundle);
        setResult(resultCode, intent);
        finish();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Bundle bundle = null;
        if (data != null) {
            bundle = data.getBundleExtra(PARAM_INTENT);
            if (bundle == null) {
                bundle = data.getExtras();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
        onActivityResult(requestCode, resultCode, bundle);
    }

    /**
     * 页面回调函数
     *
     * @param requestCode
     *         请求码
     * @param resultCode
     *         返回码
     * @param data
     *         数据
     */
    protected void onActivityResult(int requestCode, int resultCode, Bundle data) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        // TODO: 17/8/12  修改主题需要设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            mTintManager.setTintColor(0xFF00beb3);
            Drawable drawable = new ColorDrawable(0xFF00beb3);
            mTintManager.setTintDrawable(drawable);
        }
    }

    protected void initToolsBar(Toolbar mToolbar) {
        // setSupportActionBar(mToolbar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            ViewGroup.LayoutParams params = mToolbar.getLayoutParams();
            int statusHeight = mTintManager.getConfig().getStatusBarHeight();
            params.height += statusHeight;
            mToolbar.setPadding(mToolbar.getPaddingLeft(), mToolbar.getPaddingTop() +
                    statusHeight, mToolbar.getPaddingRight(), mToolbar.getPaddingBottom());
            mToolbar.setLayoutParams(params);
        }
    }

    /**
     * Apply KitKat specific translucency.
     */
    private void applyKitKatTranslucency() {

        // KitKat translucent navigation/status bar.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            mTintManager.setStatusBarTintEnabled(true);
            mTintManager.setNavigationBarTintEnabled(false);
            mTintManager.setTintColor(0xFF00beb3);
            Drawable drawable = new ColorDrawable(0xFF00beb3);
            mTintManager.setTintDrawable(drawable);

        }

    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void hideStatusBar(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }
}
